<script setup>
import {onBeforeUnmount, onMounted, reactive, ref} from "vue";
import {ElMessage} from "element-plus";
import axios from "axios";
import { v4 as uuidv4 } from 'uuid';
import {getFileExtension} from "@/api/utils.js";
import OSS from "ali-oss";
import {applyMusician} from "@/api/apply/apply.js";

const OSS_PREFIX = 'https://hfymusic.oss-cn-beijing.aliyuncs.com/'
const loading = ref(0)
const active = ref()
const types = [
  "男","女","组合","乐队","虚拟"
]
const areas = [
  "中国大陆","中国香港/澳门","日本","欧美","中国台湾","韩国","东南亚","其他"
]
const ossClient = new OSS({
  region: 'oss-cn-beijing',
  accessKeyId: 'LTAI5tFL18o8bX1ZhjUTuQgx',
  accessKeySecret: 'RUCyRoCxgAv8NQQwFNgUynZC6ATjzu',
  bucket: 'hfymusic'
})
const formValue = reactive({
  name: '',
  type: '',
  area: '中国大陆',
  brief: '',
  avatar: '',
  account: localStorage.getItem('account')
})
onMounted(() => {
  // 首先就是去查接口 看这个用户用没有音乐人身份
  // 如果有就显示上传页面
  // 如果没有就显示申请页面
})
const ruleFormRef = ref()

// 使用 ref 创建响应式数据
const valueUrl = ref()
// 创建文件输入元素
let inputElement = null;

// 方法：触发文件选择
function toGetImg() {
  if (!inputElement) {
    inputElement = document.createElement('input');
    inputElement.setAttribute('type', 'file');
    inputElement.style.display = 'none';

    inputElement.addEventListener('change', uploadFile, false);
    document.body.appendChild(inputElement);
  }
  inputElement.click();
}

// 方法：处理文件上传
function uploadFile(event) {

  const files = event.target.files;
  if (files.length <= 0) {
    ElMessage.info('请上传文件')
    return
  }
  const file = files[0];
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isLt5M) {
    ElMessage.error('上传头像图片大小不能超过 5MB!');
  } else if (!file.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件');
  } else {
    const reader = new FileReader(); // 创建读取文件对象
    reader.readAsDataURL(file); // 发起异步请求，读取文件
    reader.onload = function() { // 文件读取完成后
      valueUrl.value = this.result;
    }
    loading.value = 1;
    // 把图片文件发送给后端服务器 上传到OSS
    let filename = uuidv4()
    const suffix = getFileExtension(file.name)
    filename = filename + '.' + suffix
    const avatarUrl = OSS_PREFIX + 'img/' + `${filename}`
    ossClient.put(`music/${filename}`, file).then((res) => {
      formValue.avatar = avatarUrl
      loading.value = 0
      ElMessage.success("上传成功")
    }).catch(error => {
      console.error('上传失败:', error);
    })

  }

}

const rules = reactive({
  name: [
    { required: true, message: '请输入音乐人名字', trigger: 'blur' },
    { min: 1, max: 15, message: '名字长度必须在1-15之间', trigger: 'blur' },
  ],
  avatar: [
    {
      required: true,
      message: '请上传头像',
      trigger: 'change',
    },
  ],
  type: [
    {
      required: true,
      message: '请选择一个音乐人类型',
      trigger: 'change',
    },
  ],
  brief: [
    { required: true, message: '简介不能为空', trigger: 'blur' },
    { min: 10, max: 1000, message: '简介长度必须在10-1000字之间', trigger: 'blur' }
  ]
})

const submit = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('成功提交!')
      // 参数就是请求体formValue，发起post请求把申请音乐人请求发给后端
      applyMusician(formValue.name, formValue.type, formValue.area, formValue.brief, formValue.avatar, formValue.account).then((res)=>{
        ElMessage.success("申请成功！")
        document.location.reload()
      })
    } else {
      ElMessage.error('错误提交!', fields)
      console.log('错误提交!', fields)
    }

  })
}
</script>

<template>
    <div class="container">
      <h3>欢迎入驻FY音乐人</h3>
      <el-form class="form"
               :model="formValue"
               ref="ruleFormRef"
               :rules="rules"
      >
        <el-form-item prop="name" class="row name">
          <div class="span hi">Hi</div>
          <input v-model="formValue.name" placeholder="请输入您的歌手名" maxlength="15" style="font-size: 22px;line-height: 34px;border: 0;outline: none" >

        </el-form-item>

        <el-form-item prop="avatar" class="row avatar">
          <div class="span">头像</div>

          <div style="position: relative;" class="bigImg-div" @click="toGetImg">
            <svg v-if="loading === 1" style="position: absolute;top: 43px;left: 43px" width="24" height="24" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M24 4V8" stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/><path d="M34 6.6795L32 10.1436" stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/><path d="M41.3203 14L37.8562 16" stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/><path d="M44 24H40" stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/><path d="M41.3203 34L37.8562 32" stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/><path d="M34 41.3205L32 37.8564" stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/><path d="M24 44V40" stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/><path d="M14 41.3205L16 37.8564" stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/><path d="M6.67969 34L10.1438 32" stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/><path d="M4 24H8" stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/><path d="M6.67969 14L10.1438 16" stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/><path d="M14 6.6795L16 10.1436" stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/><animateTransform attributeName="transform" type="rotate" from="0 0 0" to="360 0 0" dur="2.2s" repeatCount="indefinite" /></svg>
            <img v-if="valueUrl" class="bigImg" :src=valueUrl>
            <img v-else class="bigImg" src="../../assets/img/icon.png">
            <div style="margin-left: 30px;display: flex;align-items: center;gap: 4px">
              <img style="line-height: 110px;width: 25px;height: 14px" src="../../assets/img/upload/upload.png">
              <span style="font-size: 11px;color: #e96161">上传</span>
            </div>
          </div>
        </el-form-item>

        <el-form-item prop="type" required class="row type">
          <div class="span">类型</div>
          <div @click="active = index;formValue.type=item" v-for="(item,index) in types" :class="{active: active === index}" :key="index" class="type-btn">
            {{ item }}
          </div>
        </el-form-item>

        <el-form-item class="row type" >
          <div class="span">地区</div>
          <el-select
              type="default"
              v-model="formValue.area"
              style="width: 360px"
              class="select"
          >
            <el-option style="font-size: 12px;"

                       v-for="item in areas"
                       :key="item"
                       :label="item"
                       :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item required style="position: relative;" class="row brief" prop="brief">
          <div style="position: absolute;top: 0" class="span">简介</div>
          <textarea placeholder="请输入一份10-1000字的个人简介" v-model="formValue.brief" minlength="10" maxlength="1000" class="brief-textarea"></textarea>
        </el-form-item>

        <div @click="submit(ruleFormRef)" class="btn">提交审核</div>

      </el-form>




    </div>


</template>

<style scoped>

.btn {
  margin-top: 30px;
  margin-left: 50%;
  transform: translateX(-50%);
  cursor: pointer;
  z-index: 6;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 120px;
  height: 40px;
  color: white;
  font-size: 16px;
  padding: 12px 20px;
  border-radius: 68px;
  background: #ff8457;
  box-sizing: border-box;
  font-family: poppin,Tahoma,Arial,\5FAE\8F6F\96C5\9ED1,sans-serif;
}
.row {
  display: flex;
  font-size: 13px;
  margin-top: 30px;

}
.span {
  width: 120px;
  padding-right: 12px;
}
.brief-textarea {
  margin-left: 132px;
  background: #f9f9fc;
  border: 0;
  outline: none;
  padding: 14px 28px;
  border-radius: 8px;
  resize: vertical;
  min-height: 46px;
  width: 500px;
  box-sizing: border-box;
  height: 100px;
  font-size: 12px;
  max-height: 250px;
  font-family: "pingfang SC", poppin, Arial, 微软雅黑, sans-serif;
}
.avatar>span {
  line-height: 110px;
}
.is-selected {
  color: #e96161!important;
}
.brief {

}
.type {
  align-items: center;
}
.type-btn {
  background: #f9f9fc;
  border: 1px solid #f9f9fc;
  padding: 9px 20px;
  border-radius: 100px;
  cursor: pointer;
  transition: 0.3s;
  width: 72px;
  height: 28.8px;
  line-height: 1;
  margin-right: 12px;
  box-sizing: border-box;
  text-align: center;
  font-size: 11px;
  color: #232323;
  position: relative
}
.type-btn:hover {
  color: #e96161;
}
.active {
  background: #f2f7ff;
  color: #e96161;
  border: 1px solid #e96161;
}
input::placeholder {
  color: #c9c9c9;
  font-weight: lighter;
}
textarea::placeholder {
  color: #a6a6a6;
  font-weight: lighter;
}
.form {
  border-radius: 10px;
  background: white;
  width: 700px;
  padding: 30px 70px;
  margin-top: 25px;
}
.name {
  border-bottom: 1px solid #efefef;
  padding-bottom: 10px;
}
.hi {
  font-weight: 600;
  width: 32px;
  display: inline-block;
  color: rgba(0, 0, 0, .65);
  text-align: left;
  font-size: 22px;
  line-height: 34px;
}
strong {
  font-size: 19px;
  font-weight: 570;
  font-family: 微軟正黑體,serif;
  letter-spacing: -1px;
}
.bigImg-div {
  width: 210px;
  cursor: pointer;
  height: 110px;
  display: flex;
}

.bigImg {
  display: block;
  width: 110px;
  height: 110px;
  border-radius: 100%;
}

.container {
  padding: 50px 100px 40px 30vw;
  box-sizing: border-box;
}
h3 {
  font-size: 22px!important;
}
</style>
